package net.chasing.androidbaseconfig.util;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;

import androidx.annotation.RequiresApi;

import net.chasing.androidbaseconfig.R;
import net.chasing.androidbaseconfig.util.glide.GlideUtils;

import java.util.List;

public class AppUtils {
    @SuppressLint("PackageManagerGetSignatures")
    private static PackageInfo getPackageInfo(Context ctx) {
        PackageInfo info = null;
        try {
            info = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(), PackageManager.GET_SIGNATURES);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return info;
    }

    /**
     * 获取版本号 4.9
     *
     * @return 当前应用的版本名称
     */
    public static String getVersionName(Context context) {
        try {
//            return getPackageInfo(context).versionName;
            return getPackageInfo(context).versionName;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 获取软件版本号(对应AndroidManifest.xml下android:VersionCode)  50
     *
     * @return 当前应用的版本id
     */
    public static long getVersionCode(Context context) {
        long versionCode = 1;
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                versionCode = getPackageInfo(context).getLongVersionCode();
            } else
                versionCode = getPackageInfo(context).versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    //获取进程名称
    public static String getProcessName(Context cxt) {
        int pid = android.os.Process.myPid();
        ActivityManager am = (ActivityManager) cxt.getSystemService(Context.ACTIVITY_SERVICE);
        if (am == null) return null;
        List<ActivityManager.RunningAppProcessInfo> runningApps = am.getRunningAppProcesses();
        if (runningApps == null) return null;
        for (ActivityManager.RunningAppProcessInfo procInfo : runningApps) {
            if (procInfo.pid == pid) {
                return procInfo.processName;
            }
        }
        return null;
    }

    /**
     * 安装apk文件
     * 如果主动请求“安装未知应用”的话，注：
     * android11在请求完“安装未知应用”权限之后会清了应用数据
     * 所以需要将安装信息进行保存，在请求完权限的时候才能进行读取安装
     */
    public static void installApk(String saveFilePath, boolean isForceUpdate) {
        installApk(FileUtils.getFileUri(ActivityUtils.getActivityUtils().currentActivity(), saveFilePath), isForceUpdate);
    }

    public static void installApk(Uri uri, boolean isForceUpdate) {
        final Activity activity = ActivityUtils.getActivityUtils().currentActivity();
        if (uri == null) {
            ToastUtils.showShort(activity, R.string.base_file_error);
            if (isForceUpdate)
                // 延迟退出应用，避免导致安装进程请求应用验证fileprovider权限失败
                new Handler(Looper.getMainLooper()).postDelayed(() -> ActivityUtils.getActivityUtils().appExit(activity), 1000);
            return;
        }

        GlideUtils.clear(activity);

        // 通过Intent安装APK文件
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        i.setDataAndType(uri, "application/vnd.android.package-archive");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        try {
            activity.startActivity(i);
            if (isForceUpdate)
                // 延迟退出应用，避免导致安装进程请求应用验证fileprovider权限失败
                new Handler(Looper.getMainLooper()).postDelayed(() ->
                        ActivityUtils.getActivityUtils().appExit(activity), 1000);
        } catch (ActivityNotFoundException e) {
            ToastUtils.showShort(activity, R.string.base_system_install_error);
        }
    }

    public static final int Code_INSTALLPACKAGES = 150;

    @RequiresApi(api = Build.VERSION_CODES.O)
    public static void startInstallPermissionSettingActivity(Activity activity) {
        Uri packageURI = Uri.parse("package:" + activity.getPackageName());
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
        activity.startActivityForResult(intent, Code_INSTALLPACKAGES);
    }

    /**
     * 不同的类型要区别获取，以下是String类型的
     *
     * @param context      上下午
     * @param metaName     meta-data定义的名字
     * @param defaultValue 默认值
     */
    public static String getAppMetaDataString(Context context, String metaName, String defaultValue) {
        try {
            //application标签下用getApplicationinfo，如果是activity下的用getActivityInfo
            //Sting类型的用getString，Boolean类型的getBoolean，其他具体看api
            return context.getPackageManager()
                    .getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA)
                    .metaData.getString(metaName, defaultValue);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return defaultValue;
        }
    }

    public static String getPackageName(Context context) {
        return context.getPackageName();
    }
}
